package com.skit.ecm.admin.activity

import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.skit.common.base.BaseActivity
import com.skit.common.bean.ActivityBean
import com.skit.common.bean.StatusResult
import com.skit.common.config.RetrofitClient
import com.skit.common.config.RouteConfig
import com.skit.common.http.HttpUtils
import com.skit.common.manager.UserManager
import com.skit.common.utils.ToastUtils
import com.skit.ecm.admin.R
import com.skit.ecm.admin.adapter.MainAdminActivityRecyclerViewAdapter
import com.skit.ecm.admin.retrofit.ActivityProtocol
import kotlinx.android.synthetic.main.admin_main_admin_activity_activity.*
import retrofit2.Call
import java.util.*

/**
 * @author shuike <a href="mailto:shuike007@gmail.com">Contact me.</a>
 * @version 1.0
 * @since  2020/6/5
 */
@Route(path = RouteConfig.AdminRoute.ACTIVITY_MANAGE)
class ActivityManageActivity : BaseActivity() {
    lateinit var activityAdapter: MainAdminActivityRecyclerViewAdapter
    private val activityList: MutableList<ActivityBean> = ArrayList()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.admin_main_admin_activity_activity)

        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        activityAdapter = MainAdminActivityRecyclerViewAdapter(activityList)
        recyclerView.adapter = activityAdapter
        recyclerView.layoutManager = LinearLayoutManager(this)

        activityAdapter.onItemClickListener = object : (View, Int) -> Unit {
            override fun invoke(p1: View, p2: Int) {
                ARouter.getInstance().build(RouteConfig.MainRoute.MAIN_ACTIVITY_DETAILS)
                    .withSerializable("bean", activityList[p2]).withBoolean("admin", true)
                    .navigation()
            }
        }

        swipeRefresh.setOnRefreshListener {
            getData()
        }
    }

    override fun onResume() {
        super.onResume()
        if (UserManager.user == null) {
            ToastUtils.showToast("请登录")
            finish()
            return
        }
        getData()
    }

    private fun getData() {
        val userProtocol: ActivityProtocol = RetrofitClient.getService(ActivityProtocol::class.java)
        val call: Call<StatusResult<List<ActivityBean>>> =
            userProtocol.getActivityList(UserManager.user?.token, 10, 10, 3)
        HttpUtils.doRequest(call) {
            swipeRefresh.isRefreshing = false
            if (it == null) {
                ToastUtils.showToast("请求失败")
                return@doRequest
            }
            if (it.isSuccess) {
                activityList.clear()
                activityList.addAll(it.data)
                activityAdapter.notifyDataSetChanged()
            }
        }
    }

}

